package com.soc.auth.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.soc.auth.domain.dto.StudentUploadData;
import com.soc.auth.domain.vo.ClassVO;
import com.soc.auth.domain.vo.PageVO;
import com.soc.auth.service.ClassService;
import com.soc.auth.service.RosterService;
import com.soc.auth.utils.CurrentUserUtil;
import com.soc.auth.utils.ResultResponse;
import com.soc.auth.domain.dto.*;
import com.sun.xml.bind.v2.TODO;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author HongZhouAn
 * @since 2023-06-05
 */
@RestController
@RequestMapping("/class")
@Validated
public class ClassController {

    private final ClassService classService;

    private final RosterService rosterService;

    public ClassController(ClassService classService, RosterService rosterService) {
        this.classService = classService;
        this.rosterService = rosterService;
    }

    /**
     * 创建班级
     */
    @PostMapping("/createClass")
    public ResultResponse<ClassVO> createClass(@RequestBody ClassCreateDTO classCreateDTO) {

        return ResultResponse.success(classService.createClass(classCreateDTO));
    }

    /**
     * 将不是老师自己创建的班级绑定到指定课程
     */
    @PostMapping("/bindCourse")
    public ResultResponse<Object> bindCourse(@Valid @RequestBody ClassBindDTO classBindDTO) {

        boolean result = classService.bindCourse(classBindDTO);
        return ResultResponse.judge(result);
    }

    /**
     * 查询当前老师所在学校下的班级
     */
    @GetMapping("/listClassPagesBySchoolId")
    public ResultResponse<PageVO<ClassVO>> listClassPagesBySchoolId(@Valid ClassSchoolPageQuery classSchoolPageQuery) {
        String schoolId = CurrentUserUtil.getCurrentUser().getSchoolId();
        PageVO<ClassVO> classVOPageVO = classService.listClassPagesBySchoolId(classSchoolPageQuery, schoolId);
        return ResultResponse.success(classVOPageVO);
    }

    /**
     * 查询当前老师所创建的班级
     */
    @GetMapping("/listClassPages")
    public ResultResponse<PageVO<ClassVO>> listClassPages(@Valid ClassTeacherPageQuery queryParams) {

        String currentUserId = CurrentUserUtil.getCurrentUser().getId();
        queryParams.setCreatorId(currentUserId);
        PageVO<ClassVO> classVOPageVO = classService.listClassPages(queryParams);
        return ResultResponse.success(classVOPageVO);
    }

    /**
     * 查询指定课程下当前老师所管理的所有班级
     */
    @GetMapping("/listClassPagesByCourseId")
    public ResultResponse<PageVO<ClassVO>> listClassPagesByCourseId(@Valid ClassCoursePageQuery queryParams) {

        String teacherId = CurrentUserUtil.getCurrentUser().getId();
        PageVO<ClassVO> classVOPageVO = classService.listClassPagesByCourseId(queryParams, teacherId);
        return ResultResponse.success(classVOPageVO);
    }

    /**
     * 删除班级
     *
     * @param classIds 要删除的班级id
     * @return 是否删除成功
     */
    @DeleteMapping("/deleteClass")
    public ResultResponse<Boolean> deleteClass(@RequestBody List<String> classIds) {
        boolean result = classService.removeClassByIds(classIds);
        return ResultResponse.judge(result);
    }

    /**
     * 修改班级名称
     */
    @PutMapping("/updateClass")
    public ResultResponse<PageVO<ClassVO>> listClassPagesByCourseId(@Valid @RequestBody ClassUpdateDTO classUpdateDTO) {

        boolean result = classService.updateClassInfo(classUpdateDTO);
        return ResultResponse.judge(result);
    }

    /**
     * 通过Excel批量导入学生加入班级
     */
    @PostMapping("/upload/{classId}")
    public ResultResponse<PageVO<ClassVO>> importStudentFromExcel(@RequestParam("file") MultipartFile excelFile, @PathVariable("classId") String classId) {
        List<StudentForm> studentFormList = new ArrayList<>();
        try {
            // 加载Excel文件
//            ExcelReader excelReader = EasyExcel.read(excelFile.getInputStream()).build();
            // 设置监听器，用于处理每一行的数据
            AnalysisEventListener<StudentUploadData> listener = new AnalysisEventListener<StudentUploadData>() {
                @Override
                public void invoke(StudentUploadData data, AnalysisContext context) {
                    // TODO: 根据需要进行业务逻辑处理
                    StudentForm studentForm = new StudentForm();
                    studentForm.setNo(data.getSno());
                    studentForm.setRealName(data.getStudentName());
                    studentFormList.add(studentForm);
                }
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    // 数据读取完成后的操作
                }
            };

            ExcelReaderBuilder excelReader = EasyExcel.read(excelFile.getInputStream(), StudentUploadData.class, listener);
            // 开始读取Excel文件
            ExcelReaderSheetBuilder sheet = excelReader.sheet();
            sheet.doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JoinClassDTO joinClassDTO = new JoinClassDTO();
        joinClassDTO.setStudentFormList(studentFormList);
        joinClassDTO.setClassId(Long.valueOf(classId));
        return ResultResponse.judge(classService.joinClassBatch(joinClassDTO));
    }

    /**
     * 修改班级下某个学生的信息（该学生必须没实名过）
     */
    @PutMapping("/student")
    public ResultResponse<Object> updateStudent(@RequestBody RosterForm rosterForm) {
        return ResultResponse.judge(rosterService.updateRoster(rosterForm));
    }

    /**
     * 删除班级下学生的信息（该学生必须没实名过）
     */
    @DeleteMapping("/student")
    public ResultResponse<Object> deleteStudent(String studentId) {
        return ResultResponse.judge(rosterService.deleteRoster(studentId));
    }

}

